import datetime

from flask import abort, request
from flask_classy import FlaskView, route

from ..extensions import oauth
from ..schema.param import create_auth_param, login_name_is_exist, ParamError
from ..schema.resp import user_schema
from ..services.auth import AuthService
from ..services.client import ClientService
from ..services.session import SessionService
from ..services.user import UserService

class AuthsView(FlaskView):
    @route('/')
    def test(self):
        return "hello"

        # def _fetch_io

    @route('/register', methods=['POST'])
    def create(self):
        data, errors = create_auth_param.load(request.get_json())
        if errors:
            return ParamError.jsonify_with(extra=errors)
        login_name = data.pop('login_name')
        password = data.pop('password')
        user_info = data.pop('user_info')

        # if not 'screen_name' in user_info:
        #     user_info['screen_name'] = 'vsogame_user'
        # if not 'head_image' in user_info:
        #     import random
        #     user_info['head_image'] =

        if AuthService.is_local_auth_exist(login_name):
            # abort(400,description=login_name_is_exist)
            return login_name_is_exist.jsonify()

        user = UserService.create_user_and_local_auth(
            screen_name=user_info.get('screen_name', 'vsogame_user'),
            head_image=user_info.get('head_image',
                                     'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1489485349862&di=b6c677295809e8aafaa507e3960c76c9&imgtype=0&src=http%3A%2F%2Fizhaowo.oss-cn-hangzhou.aliyuncs.com%2Fwww2%2Fimages%2Fpic75x75.jpg'),
            type='member',
            login_name=login_name,
            login_password=password,
            **user_info
        )
        return user_schema.jsonify(user)

    @route('/access_token', methods=['POST'])
    @oauth.token_handler
    def get_access_token(self, *args, **kwargs):
        pass
        print('tokenkeneeee')

        print(request.values)
        print(load_token(request.values.get('code')))
        code = request.values.get('code')

        # if code:
        #     grant = load_grant(request.values.get('client_id'), code)
        #     return {
        #         'type': grant.user['type'],
        #         'user_id': grant.user['id']
        #     }


@oauth.grantgetter
def grant_getter():
    pass


@oauth.grantsetter
def grant_setter():
    pass


@oauth.clientgetter
def client_getter(client_id):
    return ClientService.get_by_client_id(client_id)


@oauth.usergetter
def user_get(username, password, request=None, client=None, *args, **kwargs):
    local_auth = AuthService.fetch_local_auth_by_login_name(username)
    print(local_auth, )
    if not local_auth:
        abort(401, description='用户不存在')
    if local_auth.verify_password(local_auth.password, password):

        auth  =  local_auth.auth
        if not auth:
            abort(401)

        local_auth.retry_count = 0
        local_auth.last_retry_time = datetime.datetime.now()
        AuthService.save_local_auth(local_auth)
        return auth
    else:
        local_auth.retry_count += 1
        local_auth.last_retry_time = datetime.datetime.now()
        AuthService.save_local_auth(local_auth)
        abort(401, description='密码不正确')


@oauth.tokengetter
def load_token(access_token=None, refresh_token=None):
    if access_token:
        return SessionService.get_token(access_token=access_token)
    if refresh_token:
        return SessionService.get_token(refresh_token=refresh_token)


@oauth.tokensetter
def save_token(token, request, *args, **kwargs):
    if request:
        token.setdefault('user_id', request.user.profile_id)
    SessionService.save_token(**token)


def create_grant_id(client_id, code):
    return 'grant.{}.{}'.format(client_id, code)


def create_access_token_id(token):
    return 'access_token.{}'.format(token)


def create_refresh_token_id(token):
    return 'refresh_token.{}'.format(token)
